package org.ma1.cripto.aes.gui.dialogos;

import java.awt.Color;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.ma1.cripto.aes.comun.Clave;
import org.ma1.cripto.aes.gui.Parametros;

public class ConfigurarDialog implements IDialogo {
	public ConfigurarDialog() {
	}

	public void execute() {
		JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
		panel.add(new JLabel("Clave:"));
		JTextField tt = new JTextField();
		panel.add(tt);
		JLabel adv = new JLabel("32 caracteres en hexadecimal");
		adv.setForeground(Color.blue.darker());
		panel.add(adv);
		panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 100, 10));
		String string1 = "Aceptar";
		String string2 = "Cancelar";
		String string3 = "Clave aleatoria";
		Object[] options = { string1, string2, string3 };
		boolean salir = true;
		do {
			tt.setText(calcularClave());
			int n = JOptionPane.showOptionDialog(null, panel,
					"Seleccion de clave", JOptionPane.YES_NO_OPTION,
					JOptionPane.QUESTION_MESSAGE, new ImageIcon(
							ColoresDialog.class
									.getResource("res/configurar.png")),
					options, string1);
			if (n == 0) {
				salir = procesarAceptar(tt.getText(), adv);
			} else if (n == 2) {
				generaClaveAleatoria();
				salir = false;
			} else {
				salir = true;
			}
		} while (!salir);

	}

	private String calcularClave() {
		Clave c = (Clave)Parametros.getCurrentInstance().getParametro("clave");
		String cl = "";
		for (int k=0; k<c.getTamBloque(); k++) {
			String token = Integer.toHexString((int)c.getByte(k));
			if (token.length()==1) {
				token = "0"+token;
			} else if (token.length()>2) {
				token = token.substring(token.length()-2);
			}
			cl +=  token.toUpperCase() + " ";
		}
		return cl;
	}

	private void generaClaveAleatoria() {
		Random r = new Random();
		Clave clave = (Clave)Parametros.getCurrentInstance().getParametro("clave");
		for (int i=0; i<clave.getTamBloque(); i++) {
			clave.setByte(i,(byte)(r.nextInt()&0xFF));
		}
		Parametros.getCurrentInstance().putParametro("clave",clave);
	}

	// devuelve OK o NO_OK
	private boolean procesarAceptar(String tt, JLabel adv) {
		Clave clave = new Clave();
		boolean b = true;
		adv.setForeground(Color.red);
		Parametros param = Parametros.getCurrentInstance();
		int n = ((Clave) param.getParametro("clave")).getTamBloque();
		StringTokenizer st = new StringTokenizer(tt);
		int cont = 1;
		if (n != st.countTokens()) {
			adv.setText("La longitud debe ser de 32 bytes (hex)");
			b = false;
		} else {
			while(st.hasMoreTokens() && b) {
				String token = st.nextToken();
				Pattern patron = Pattern.compile("^([0-9]|[A-F]|[a-f]){2}");
				b = patron.matcher(token).matches();
				if (b) {
					clave.setByte(cont-1,(byte)(Integer.parseInt(token,16)&0xFF));
				}
				cont++;
			}
			if (!b) {
				adv.setText("Los caracteres deben estar en hexadecimal ("+cont+")");
			}
		}

		if (b) {
			param.putParametro("clave",clave);
		}
		
		return b;
	}
}
